import tui from '../common/httpRequest'
import { baseHostURL, baseURL, tabbar, loginToUrl, cproject, host } from "@/utils/config";


//缓存提示信息

export function cacheMessage(title = 'Fail', content = 'Fail Message', type = 0) {
    uni.setStorageSync("cacheMessage", {
        title: title,
        content: content,
        type: type
    });
}


//格式化字符串
export function hiddenStr(str, front = 5, back = 5, star = '****') {
    return str.length > front + back ? str.slice(0, front) + star + str.slice(back * -1) : str;
};

//获取不同端的跳转页面
export function getClientUrl(type, id) {
    var url = "";
    //收银台
    if (type == 'cshou') {
        // #ifdef H5
        if (isWeixin()) {
            url = "/pages/common/cshou/wxh5?id=" + id;
        } else {
            url = "/pages/common/cshou/wap?id=" + id;
        }
        // #endif

        // #ifdef MP-WEIXIN
        url = "/pages/common/cshou/xcx?id=" + id;
        // #endif

        // #ifdef APP-PLUS
        url = "/pages/common/cshou/app?id=" + id;
        // #endif
    }
    return url;
}
//获取客户端
export function getClient() {
    var client = ""
        // #ifdef H5
    if (isWeixin()) {
        client = "wxh5"
    } else {
        client = "wap"
    }
    // #endif

    // #ifdef MP-WEIXIN
    client = "xcx"
        // #endif

    // #ifdef APP-PLUS
    client = "app"
        // #endif
    return client
}
//获取域名
export function getHost() {
    var hosts = host
    if (window && window.location && window.location.hostname) {
        hosts = window.location.hostname
    }
    return hosts
}
//小程序登录code
export async function getXcxLoginCode() {
    uni.login({
        provider: 'weixin',
        success: async(res) => {
            uni.setStorageSync('xcx_login_code', res.code)
        }
    });
}
//小程序授权登录,数据
export async function getXcxLoginData(callback) {
    await getXcxLoginCode()
    uni.getUserProfile({
        desc: '用于完善会员资料',
        success: async(r) => {
            var tid = uni.getStorageSync('tid');
            tid = tid ? tid : 0
            var code = uni.getStorageSync('xcx_login_code');
            let data = {
                tid: tid,
                code: code,
                userinfo: r.userInfo,
            };
            uni.setStorageSync('xcx_login_data', data)
            callback()
        },
        fail: async(res) => {
            error('授权失败');
        }
    });
}
//网页 微信h5授权
export async function wxh5code(type, back_url = '') {
    if (!isWeixin()) {
        return error('wap端暂不支持微信登录');
    }

    back_url = back_url ? back_url : "/pages/tabbar/index/index"
    back_url = window.location.origin + "/" + cproject + "/#" + back_url
    uni.setStorageSync('h5code_back_url', back_url)
    var data = {}
    var url = ""
    var redirect_url = window.location.origin + "/" + cproject + "/#/pages/common/h5code/h5code?type=" + type
        //登录授权
    if (type == 'login') {
        data = {
            redirect_url: redirect_url
        }
        url = await $post(data, "/Api/COMAPP/Wx/getCodeUrlForGetUserInfo", true)
            //微信绑定	
    } else if (type == 'bindwx') {
        data = {
            redirect_url: redirect_url
        }
        url = await $post(data, "/Api/COMAPP/Wx/getCodeUrlForGetUserInfo", true)

    } else if (type == 'pay') {
        data = {
            redirect_url: redirect_url
        }
        url = await $post(data, "/Api/COMAPP/Wx/getCodeUrl", true)
    }
    window.location.href = url;
}
/**
 * 请求函数
 * data:数据
 * url:链接地址
 * isBaseUrl:是否公共接口，
 * showLoading: 显示loading
 */
export async function $post(data, url, isBaseUrl = false, showLoading = false, isDealError = false) {
    if (url.indexOf('http') === -1) {
        url = isBaseUrl ? baseHostURL + url : baseURL + url
    }
    let hideLoading = !showLoading
    let rs = await tui.request(url, 'POST', data, false, true, hideLoading)

    if (rs.code == undefined && rs.data == undefined) return rs;
    if (rs.code != 200) {
        if (rs.code == -4) {
            logoutSuccess();
            return { list: [], total: 0, tg_url: [], data: [] }
        }
        if (isDealError) {
            isDealError(rs)
        } else {
            await error(rs.msg)
        }
        throw true
    } else {
        return rs.data
    }
}
/**
 * 请求函数
 * data:数据
 * url:链接地址
 * showLoading: 显示loading
 */
export async function $posts(data, url, showLoading = false) {
    let hideLoading = !showLoading
    let rs = await tui.request(baseHostURL + url, 'POST', data, false, true, hideLoading)
    return rs
}
//获取数据对象的配置
export async function $getTabCon(tab, key) {
    let str = tab + key
    let res = await $post({ tab: tab, key: key }, "/Api/COMAPP/Config/getTabConfig", true)
    return res
}

//获取app的配置,比如第三方接口配置
export async function $getAppCon(uuid, key = '') {
    let res = await $post({ uuid: uuid }, "/Api/COMAPP/CApp/getInfoByUuid", true)
    if (key) {
        return res[key]
    }
    return res
}

//获取系統數據，比如imgurl,hosturl
export async function $getCon(key) {
    // let res = await $post({}, "/Api/COMAPP/Config/getCom", true)
    // if (key) {
    //     return res[key]
    // }
    // return res
}

//获取当页列表
export async function $getCPage(uuid, page, page_size) {
    let res = await $post({ uuid: uuid, page: page, page_size: page_size }, "/Api/COMAPP/CPage/getInfoByUuid", true)
    return res
}
//获取单页
export async function $getCPageById(id = 0, ext = '') {
    let res = await $post({ id: id, ext: ext }, "/Api/COMAPP/CPage/getInfoById", true)
    return res
}

//获取頁面文字配置
export async function $getCTxt(uuid, key = '') {
    let res = await $post({ uuid: uuid }, "/Api/COMAPP/CTxt/getInfoByUuid", true)
    if (key) {
        return res[key]
    }
    return res
}
//获取app的公共接口数据,slide,nav,ad
export async function $getCNav(type, uuid) {
    let res = await $post({ type: type, uuid: uuid }, "/Api/COMAPP/CNav/getInfoByUuid", true)
    return res
}
//获取推荐位数据
export async function $getTj(uuid, page, page_size) {
    let res = await $post({ uuid: uuid, page: page, page_size: page_size }, "/Api/COMAPP/CPosition/getInfoByUuid", true, false)
    return res
}

// //获取图片,视频绝对路径
// export async function getPath(path){
// 	 if(path.indexOf('http')!=-1){
// 		return path
// 	}
// 	let imgurl = await $getCon('imgurl')
// 	let url = imgurl + path
// console.log(url)
// 	return url;

// }

//登录成功
export async function loginSuccess(res) {
    uni.setStorageSync('token', res)
    var url = loginToUrl
    if (uni.getStorageSync('nologin_back_url')) {
        url = uni.getStorageSync('nologin_back_url')
    }
    success('login Success', url, 1)
}
export function logoutSuccess() {

    uni.setStorageSync('token', '');

    uni.showModal({
        title: "need Login",
        content: 'click ok to home',
        confirmText: 'ok',
        showCancel: false,
        success(res) {
            if (res.confirm) {
                goto("/");
            }
        }
    });
}
export function isLogin() {
    let rs = uni.getStorageSync('token')
    return rs ? true : false
}

//数据是否为空[string,array,object]
export function isNull(param) {
    //字符串
    if (!param ||
        param == undefined ||
        param == null ||
        param == "" ||
        param.trim() == ""
    ) {
        return false;
    }
    //数组
    if (Array.isArray(param) && param.length == 0) {
        return false;
    }
    //对象
    if (JSON.stringify(data) == "{}") {
        return false;
    }
    return true;
}

export function myFixed(num, digit) {  
    if (Object.is(parseFloat(num), NaN)) {     return console.log(`传入的值：${num}不是一个数字`);   }  
    num = parseFloat(num);  
    return (Math.round((num + Number.EPSILON) * Math.pow(10, digit)) / Math.pow(10, digit)).toFixed(digit);
}

//显示loading
export function showLoading(txt, callback) {
    txt = txt ? txt : "";
    uni.showLoading({
        title: txt,
        success(res) {
            callback && callback(res);
        },
    });
}

// export function richFilter(val, imgurl) {
//   if (!val || !imgurl) {
//     return;
//   }
//   const newVal = val.replace(/src=\"/g, 'src="' + imgurl + "");
//   return newVal;
// }

//显示提示
export function showToast(title) {
    uni.showToast({
        title,
        icon: "none",
        duration: 2000,
    });
}

//分隔回车和逗号函数
export function explode(rule = /[\n,]/g, str) {
    var temp = str.split(rule);
    for (var i = 0; i < temp.length; i++) {
        if (temp[i] == "") {
            temp.splice(i, 1);
            i--;
        }
    }
    return temp;
}
/**
 * 微信code
 */
export async function getWxLoginCode() {
    const js_code = await new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            success: res => {
                resolve(res.code);
            },
            fail: err => {
                reject(err);
            }
        });
    });
    return js_code;
}
//是否是微信
export function isWeixin() {
    let target = window.navigator.userAgent.toLowerCase();
    return /micromessenger/.test(target) ? true : false;
}
//获取参数
export function getUrlParam(variable, url) {
    if (url) {
        if (url.indexOf('?') != -1) {
            var query = url.split("?");
            query = query[1];
        } else {
            var query = url;
        }
    } else {
        var query = window.location.search.substring(1);
    }
    let vars = query.split("&");

    let re = false;
    vars.forEach((item) => {
        let pair = item.split("=");
        if (pair[0] == variable) {
            re = pair[1];
            return;
        }
    });
    return re;
}
//跳转函数
export function goto(url) {
    if (url === -1) {
        return uni.navigateBack();
    };
    // const tabArr = tabbar;
    var type = "";
    // tabArr.forEach((e, i) => {
    //     if (url.includes(e)) {
    //         type = "switchTab";
    //     }
    // });
    if (type === "") {
        uni.navigateTo({ url });
    } else if (type == "switchTab") {
        var id = getUrlParam("id", url);
        if (id != '') uni.setStorageSync("id", id);
        uni.switchTab({ url });
    }
}
//操作成功后提示后跳转
export function success(msg = "操作成功！", path = "", seconds = 3) {
    msg = msg + ''
    const time = 1000;
    uni.showToast({
        icon: "success",
        title: msg,
        duration: seconds * time,
    });
    if (path) {
        setTimeout(() => {
            goto(path);
        }, seconds * time);
    }
}
//错误提示跳转
export function error(msg = "", path = false, seconds = 3) {
    msg = msg + ''
    const time = 1000;
    uni.showToast({
        icon: "error",
        title: msg,
        duration: seconds * time,
    });
    if (path) {
        setTimeout(() => {
            goto(path);
        }, seconds * time);
    }
    return false;
}
/**
 * 数组查找
 * @param  {[type]} search [description]
 * @param  {[type]} array  [description]
 * @return {[type]}        [description]
 */
export function in_array(search, array) {
    for (var i in array) {
        if (array[i] == search) {
            return true;
        }
    }
    return false;
}

//对象转数组
export function toArray(data) {
    let arr = [];
    for (var i in data) {
        arr.push(data[i]);
    }
    return arr;
}


export function copy(text) {
    var oInput = document.createElement('input');
    oInput.value = text;
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand("Copy");
    oInput.className = 'oInput';
    oInput.style.display = 'none';
    success('copy success! ');
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
    if (!source && typeof source !== "object") {
        throw new Error("error arguments", "deepClone");
    }
    const targetObj = source.constructor === Array ? [] : {};
    Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === "object") {
            targetObj[keys] = deepClone(source[keys]);
        } else {
            targetObj[keys] = source[keys];
        }
    });
    return targetObj;
}
//格式化价格
export function forMatPrice(val = 0) {
    if (!val ||
        val == null ||
        val == undefined ||
        val == "undefined" ||
        isNaN(val)
    ) {
        return 0;
    }
    return parseFloat(val) - 0;
}


/**
 * @description 模仿PHP的strtotime()函数
 * strtotime('2012-07-27 12:43:43') OR strtotime('2012-07-27')
 * @return 时间戳
 */
export function strtotime(str) {
    var _arr = str.split(' ');
    var _day = _arr[0].split('-');
    _arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
    var _time = _arr[1].split(':');
    for (var i = _day.length - 1; i >= 0; i--) {
        _day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
    }
    for (var i = _time.length - 1; i >= 0; i--) {
        _time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
    }
    var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
    return _temp.getTime() / 1000;
}

/**
 * 格式化时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
    if (time == 0) return "";
    if (arguments.length === 0) {
        return null;
    }
    const format = cFormat || "{y}-{m}-{d} {h}:{i}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string" && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        }
        if (typeof time === "number" && time.toString().length < 11) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        if (result.length > 0 && value < 10) {
            value = "0" + value;
        }
        return value || 0;
    });
    return time_str;
}
//是否是数组
export function isArray(o) {
    return Object.prototype.toString.call(o) == '[object Array]';
}

/**
 * 修改json key值
 * @param  {[type]}  arr         [description]
 * @param  {[type]}  old_key     [description]
 * @param  {[type]}  new_key     [description]
 * @return {[type]}              [description]
 */
export function changeJsonKey(arr, old_key, new_key) {
    arr = arr.slice();

    function toParse(arr) {
        arr.forEach(function(item) {
            item[new_key] = item[old_key];
            delete item[old_key];
            if (old_key == "children") {
                toParse(item[new_key]);
            } else if (item.children && Array.isArray(item.children)) {
                if (item.children.length > 0 && item.children[0] != undefined) {
                    toParse(item.children);
                } else {
                    delete item.children;
                }
            }
        });
        return arr;
    }
    return toParse(arr);
}

/**
 * 递归获取json树形结构的key值
 * @param  {[type]} arr [description]
 * @param  {[type]} key [description]
 * @param  {[type]} val [description]
 * @return {[type]}     [description]
 */
export function getTreeKey(arr, key, val) {
    arr = arr.slice();

    function toParse(arr, cur) {
        for (let i = 0; i < arr.length; i++) {
            let item = arr[i];
            cur.push(item[key]);
            if (item[key] == val) {
                return cur;
            } else {
                //当有下一级数据时,递归判断
                if (item.children && Array.isArray(item.children)) {
                    if (item.children.length > 0 && item.children[0] != undefined) {
                        //查找到数据,则返回数组
                        let rs = toParse(item.children, cur);
                        if (rs.length > 0) {
                            return rs;
                        }
                    } else {
                        delete item.children;
                    }
                } else {
                    //当没有下一级数据, 并且为最后一条数据的时候,清空全部
                    if (i == arr.length - 1) {
                        cur.splice(0, cur.length);
                        //当没有下一级数据, 并且不为最后一条数据的时候,删除最后一个无用数据
                    } else {
                        cur.splice(cur.length - 1, 1);
                    }
                }
            }
        }
        return [];
    }
    return toParse(arr, []);
}

/**
 * 删除自身,key
 * @param  {[type]} arr [description]
 * @param  {[type]} key [description]
 * @param  {[type]} val [description]
 * @return {[type]}     [description]
 */
export function deleteJsonKey(arr, key, val) {
    arr = arr.slice();

    function toParse(arr) {
        arr.forEach(function(item, index, array) {
            if (item[key] == val) {
                array.splice(index, 1);
            } else if (item.children && Array.isArray(item.children)) {
                if (item.children.length > 0 && item.children[0] != undefined) {
                    toParse(item.children);
                } else {
                    delete item.children;
                }
            }
        });
        return arr;
    }
    return toParse(arr);
}

//删除子数组
export function deleteChildren(arr) {
    arr = arr.slice();

    function toParse(arr) {
        arr.forEach(function(item, index, array) {
            if (
                item.children &&
                Array.isArray(item.children) &&
                item.children.length > 0
            ) {
                toParse(item.children);
            } else {
                delete item.children;
            }
        });
        return arr;
    }
    return toParse(arr);
}

//数组去重
export function uniqueArr(arr) {
    return Array.from(new Set(arr));
}
//打电话
export function phoneCall(phoneNumber) {
    uni.makePhoneCall({
        phoneNumber: phoneNumber,
    });
}
//显示图片
export function showPic(pics, index) {
    uni.previewImage({
        current: index,
        urls: pics
    })
}
//需登录
export function needLogin() {
    if (isLogin()) return true
    uni.showModal({
        title: '登录提示',
        content: '确定要登录吗?',
        confirmText: "确定",
        success: async(res) => {
            if (res.confirm) {
                goto('/pages/common/login/login');
                return false
            } else if (res.cancel) {
                return false
            }
        }
    });
    return false
}

// 下划线转换驼峰
export function toHump(name) {
    return name.replace(/\_(\w)/g, function(all, letter) {
        return letter.toUpperCase();
    });
}
// 驼峰转换下划线
export function toLine(name) {
    return name.replace(/([A-Z])/g, "_$1").toLowerCase();
}
/**
 *  查看图片
 * @param {*} i 图片索引
 * @param {*} data 图片（数组）
 * @returns 
 */
export function previewImg(i, data) {
    if (!i) return
    uni.previewImage({
        current: i,
        urls: data
    })
}